import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:isolate/isolate.dart';
import 'package:test_performance/ui/my_isolate.dart';

/*
 * @Author: zhudaihao
 * @Date: 2022/3/5
 * @Describe: isolate测试
 */

void main() {
  runApp(MaterialApp(
    builder: (context, child) {
      return const Test3Isolate();
    },
  ));
}

class Test3Isolate extends StatefulWidget {
  const Test3Isolate({Key? key}) : super(key: key);

  @override
  State<Test3Isolate> createState() => _Test3IsolateState();
}

class _Test3IsolateState extends State<Test3Isolate> {
  String result = "";
  String tagResult = "";

  ///创建LoadBalancer线程池
  Future<LoadBalancer> loadBalancer =
      LoadBalancer.create(2, IsolateRunner.spawn);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: SizedBox(
          width: double.infinity,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const Padding(
                padding: EdgeInsets.all(8.0),
                child: CircularProgressIndicator(),
              ),
              Text("点击计算结果：$result"),
              ElevatedButton(
                  onPressed: () {
                    //同步执行
                    // result = sum(1000000000);
                    //异步执行
                    sum2(1000000000);

                    ///使用封装的isolate：compute
                    // compute(computeData, 1000000000);

                    // debugPrint('result:$result');
                    // if (result.isNotEmpty && result != tagResult) {
                    //   setState(() {
                    //     tagResult = result;
                    //     debugPrint('result222:$result');
                    //   });
                    // }

                    ///isolater
                    // setMyIsolate();

                    ///IsoLater的线程池
                    // getResult();

                    debugPrint('------------ElevatedButton');
                  },
                  child: const Text("点击按钮")),
            ],
          ),
        ));
  }

  ///线程池
  getResult() async {
    LoadBalancer balancer = await loadBalancer;
    String res = await balancer.run<String, int>((argument) {
      debugPrint('-----------$argument');
      String date = sum(1000000000);
      return date;
    }, 1);

    setState(() {
      result = res;
    });
  }

  setMyIsolate() async {
    await computeMyIsolate(success: (date) {
      result = date;
      if (result.isNotEmpty && result != tagResult) {
        setState(() {
          tagResult = result;
          debugPrint('result222:$result');
        });
      }
    });
  }
}

///同步方法
String sum(int num) {
  int count = 0;
  while (num > 0) {
    count = count + num;
    num--;
  }
  return count.toString();
}

///异常任务 执行耗时任务
Future<String> sum2(int num) async {
  int count = 0;
  debugPrint('-------sum2');
  return Future<String>(() {
    while (num > 0) {
      count = count + num;
      num--;
    }
    debugPrint('-------sum3');
    return count.toString();
  });
}

///compute 方法
String computeData(int num) {
  return sum(num);
}
